let winners = new Set(); // 存储所有已中奖的员工编号

class LotterySystem {
    constructor() {
        this.rounds = [];
        // 第一组：3轮，每轮10人
        for (let round = 1; round <= 3; round++) {
            this.rounds.push({
                name: '第一组',
                subName: `第${this.getChineseNumber(round)}轮`,
                count: 10,
                chinese: '一',
                group: 1,
                round: round
            });
        }
        // 第二组：3轮，每轮10人
        for (let round = 1; round <= 3; round++) {
            this.rounds.push({
                name: '第二组',
                subName: `第${this.getChineseNumber(round)}轮`,
                count: 10,
                chinese: '二',
                group: 2,
                round: round
            });
        }
        // 第三组：4轮，每轮10人
        for (let round = 1; round <= 4; round++) {
            this.rounds.push({
                name: '第三组',
                subName: `第${this.getChineseNumber(round)}轮`,
                count: 10,
                chinese: '三',
                group: 3,
                round: round
            });
        }

        this.currentRound = 0;
        this.employees = [];
        this.winners = new Set();
        this.isRolling = false;
        this.rollInterval = null;
        this.currentWinners = [];
        this.isRoundFinished = false;
        this.allWinners = []; // 存储所有获奖记录
        this.isFullscreen = false;
        this.fullscreenInitialized = false;
        this.isFileLoaded = false;

        // 添加每组总人数的配置
        this.groupTotalCount = {
            1: 30,  // 第一组 3轮，每轮10人，共30人
            2: 30,  // 第二组 3轮，每轮10人，共30人
            3: 40   // 第三组 4轮，每轮10人，共40人
        };
    }

    // 添加中文数字转换方法
    getChineseNumber(num) {
        const chinese = ['一', '二', '三', '四', '五'];
        return chinese[num - 1] || num.toString();
    }

    // 添加提示信息的方法
    showStartTip() {
        const resultBox = document.getElementById('resultBox');
        resultBox.innerHTML = '';
        const tipDiv = document.createElement('div');
        tipDiv.style.cssText = `
            color: rgba(212, 54, 59, 0.6);
            font-size: 40px;
            text-align: center;
            width: 100%;
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            font-family: "方正正粗黑简体", "FZZhengHeiS-B-GB", sans-serif;
        `;
        tipDiv.textContent = '开始抽奖';
        resultBox.appendChild(tipDiv);
    }

    async init() {
        // 移除一次性的点击事件监听，改为持续监听直到文件加载成功
        document.addEventListener('click', () => {
            if (!this.isFileLoaded) {
                this.loadEmployees().catch(error => {
                    console.error('加载员工数据失败:', error);
                });
            }
        }); // 移除 { once: true }

        // 设置抽奖按键监听
        document.addEventListener('keydown', (e) => this.handleKeyPress(e));

        // 监听全屏状态变化
        const handleFullscreenChange = () => {
            this.isFullscreen = !!(
                document.fullscreenElement ||
                document.webkitFullscreenElement ||
                document.mozFullScreenElement ||
                document.msFullscreenElement
            );
        };

        document.addEventListener('fullscreenchange', handleFullscreenChange);
        document.addEventListener('webkitfullscreenchange', handleFullscreenChange);
        document.addEventListener('mozfullscreenchange', handleFullscreenChange);
        document.addEventListener('MSFullscreenChange', handleFullscreenChange);

        // 显示点击提示
        this.showClickTip();
    }

    // 添加点击提示的方法
    showClickTip() {
        const resultBox = document.getElementById('resultBox');
        resultBox.innerHTML = '';
        const tipDiv = document.createElement('div');
        tipDiv.style.cssText = `
            color: rgba(212, 54, 59, 0.6);
            font-size: 36px;
            text-align: center;
            width: 100%;
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            font-family: "方正正粗黑简体", "FZZhengHeiS-B-GB", sans-serif;
        `;
        tipDiv.textContent = '点击页面选择员工编码文件';
        resultBox.appendChild(tipDiv);
    }

    async loadEmployees() {
        try {
            // 获取并播放背景音乐
            const backgroundMusic = document.getElementById('backgroundMusic');
            backgroundMusic.play().catch(error => {
                console.log('无法播放音乐:', error);
            });

            // 创建文件选择Promise
            const fileData = await new Promise((resolve, reject) => {
                const fileInput = document.getElementById('fileInput');
                fileInput.value = ''; // 清空之前的选择

                fileInput.onchange = (e) => {
                    const file = e.target.files[0];
                    if (file) {
                        const reader = new FileReader();
                        reader.onload = (event) => {
                            resolve(event.target.result);
                        };
                        reader.onerror = (error) => {
                            reject(error);
                        };
                        reader.readAsArrayBuffer(file);
                    } else {
                        reject(new Error('未选择文件'));
                    }
                };

                fileInput.click();
            });

            // 解析Excel文件
            const workbook = XLSX.read(fileData, { type: 'array' });

            // 获取第一个sheet
            const firstSheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[firstSheetName];

            // 将工作表转换为数组，从第二行开始（跳过表头）
            const jsonData = XLSX.utils.sheet_to_json(worksheet, {
                header: 1,
                range: 1
            });

            // 提取员工编码和姓名
            this.employees = jsonData
                .filter(row => row[0] && typeof row[0] === 'string' && row[0].trim() !== '')
                .map(row => ({
                    code: row[0],
                    name: row[1] || '未知'  // 如果没有姓名则显示"未知"
                }));

            console.log(`成功加载 ${this.employees.length} 个员工信息`);

            if (this.employees.length === 0) {
                throw new Error('Excel文件中没有有效的员工编码');
            }

            this.isFileLoaded = true;  // 只有在成功加载文件后才设置为 true
            this.updateRoundInfo();
            await this.enterFullscreen();
            this.fullscreenInitialized = true;
            this.showStartTip();

        } catch (error) {
            console.error('读取员工编码文件失败:', error);
            // 如果出错，停止音乐播放
            const backgroundMusic = document.getElementById('backgroundMusic');
            backgroundMusic.pause();
            backgroundMusic.currentTime = 0;

            this.showClickTip();
        }
    }

    updateRoundInfo() {
        const round = this.rounds[this.currentRound];
        document.getElementById('prizeTitle').textContent = `${round.name} ${round.subName}`;
        document.getElementById('prizeCount').textContent = `共计${this.groupTotalCount[round.group]}名`;
    }

    // 根据人数获取布局样式
    getLayoutStyle(count) {
        if (count > 20) {
            return {
                className: 'three-columns',
                fontSize: '30px'
            };
        } else if (count > 10) {
            return {
                className: 'two-columns',
                fontSize: '36px'
            };
        } else {
            return {
                className: 'one-column',
                fontSize: '35px'
            };
        }
    }

    // 添加一个格式化姓名的辅助方法
    formatName(name) {
        if (name.length === 2) {
            const spacer = '&nbsp;&nbsp;&nbsp;&nbsp;'; // 6个&nbsp;
            const div = document.createElement('div');
            div.style.display = 'inline';
            div.innerHTML = `${name[0]}${spacer}${name[1]}`;
            return div.innerHTML;
        }
        return name;
    }

    startRolling() {
        if (this.isRolling) return;
        this.isRolling = true;

        const resultBox = document.getElementById('resultBox');
        resultBox.innerHTML = '';

        const round = this.rounds[this.currentRound];
        this.currentWinners = [];

        // 获取布局样式
        const style = this.getLayoutStyle(round.count);
        resultBox.className = `result-box ${style.className}`;

        // 创建包装容器
        const wrapper = document.createElement('div');
        wrapper.className = 'winners-wrapper';
        wrapper.style.display = 'grid';
        wrapper.style.gridTemplateColumns = 'repeat(2, 1fr)'; // 设置为两列
        wrapper.style.gap = '10px'; // 设置列间距
        resultBox.appendChild(wrapper);

        // 创建10个占位元素，分两列显示
        for(let i = 0; i < round.count; i++) {
            const winnerDiv = document.createElement('div');
            winnerDiv.className = 'winner-item';
            winnerDiv.style.fontSize = style.fontSize;
            winnerDiv.style.textAlign = 'center';
            wrapper.appendChild(winnerDiv);
        }

        const winnerItems = wrapper.getElementsByClassName('winner-item');

        this.rollInterval = setInterval(() => {
            // 随机生成10个不重复的员工
            const tempWinners = this.getMultipleWinners(round.count);
            tempWinners.forEach((winner, index) => {
                winnerItems[index].innerHTML = `${winner.code} ${this.formatName(winner.name)}`;
            });
        }, 50);
    }

    stopRolling() {
        if (!this.isRolling) return;
        clearInterval(this.rollInterval);
        this.isRolling = false;

        const round = this.rounds[this.currentRound];
        const resultBox = document.getElementById('resultBox');
        resultBox.innerHTML = '';

        // 获取布局样式
        const style = this.getLayoutStyle(round.count);
        resultBox.className = `result-box ${style.className}`;

        // 创建包装容器
        const wrapper = document.createElement('div');
        wrapper.className = 'winners-wrapper';
        wrapper.style.display = 'grid';
        wrapper.style.gridTemplateColumns = 'repeat(2, 1fr)'; // 设置为两列
        wrapper.style.gap = '10px'; // 设置列间距
        resultBox.appendChild(wrapper);

        // 获取10个不重复的获奖者
        this.currentWinners = this.getMultipleWinners(round.count);

        // 记录获奖信息并创建双列显示
        this.currentWinners.forEach(winner => {
            this.addWinnerRecord(winner, round);
            const winnerDiv = document.createElement('div');
            winnerDiv.className = 'winner-item';
            winnerDiv.style.fontSize = style.fontSize;
            winnerDiv.style.textAlign = 'center';
            winnerDiv.innerHTML = `${winner.code} ${this.formatName(winner.name)}`;
            wrapper.appendChild(winnerDiv);
            this.winners.add(winner.code);  // 只存储编码用于去重
        });

        this.showFireworks();
        this.isRoundFinished = true;

        // 每轮结束后自动保存结果
        this.exportToExcel();

        // 如果是最后一轮，延迟一段时间后再次保存结果
        if (this.currentRound === this.rounds.length - 1) {
            setTimeout(() => {
                this.exportToExcel();
            }, 2000);
        }
    }

    getMultipleWinners(count) {
        const availableEmployees = this.employees.filter(e => !this.winners.has(e.code));
        const winners = [];

        // 随机抽取指定数量的获奖者
        for(let i = 0; i < count && availableEmployees.length > 0; i++) {
            const randomIndex = Math.floor(Math.random() * availableEmployees.length);
            winners.push(availableEmployees[randomIndex]);
            availableEmployees.splice(randomIndex, 1);
        }

        return winners;
    }

    getRandomEmployee() {
        const availableEmployees = this.employees.filter(e => !this.winners.has(e.code));
        const randomIndex = Math.floor(Math.random() * availableEmployees.length);
        return availableEmployees[randomIndex];
    }

    handleKeyPress(event) {
        if (event.key === 'Enter') {
            if (this.isRolling) {
                this.stopRolling();
            } else if (this.isRoundFinished) {
                // 如果当前轮次已完成，按回车进入下一轮
                this.startNextRound();
            } else {
                // 否则开始抽奖
                this.startRolling();
            }
        } else if (event.key === ' ') { // 添加空格键控制
            // 防止空格键触发页面滚动
            event.preventDefault();
            this.toggleBackgroundMusic();
        }
    }

    createFirework(x, y) {
        const colors = ['#ff0', '#ffd700', '#ff4500', '#ff69b4', '#00ff00', '#fff'];
        const firework = document.createElement('div');
        firework.className = 'firework';
        firework.style.left = x + 'px';
        firework.style.top = y + 'px';
        firework.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];

        // 增加粒子数量
        for (let i = 0; i < 40; i++) {
            const particle = document.createElement('div');
            particle.className = 'particle';
            const angle = (i * 9) * Math.PI / 180; // 调整角度使粒子分布更均匀
            const velocity = 80 + Math.random() * 80; // 增加粒子扩散范围
            const tx = Math.cos(angle) * velocity;
            const ty = Math.sin(angle) * velocity;

            particle.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
            particle.style.setProperty('--tx', `${tx}px`);
            particle.style.setProperty('--ty', `${ty}px`);

            firework.appendChild(particle);
        }

        document.getElementById('fireworksContainer').appendChild(firework);

        setTimeout(() => {
            firework.remove();
        }, 1200); // 延长清理时间
    }

    showFireworks() {
        const resultBox = document.getElementById('resultBox');
        const rect = resultBox.getBoundingClientRect();

        // 在结果区域内创建多个烟花
        for (let i = 0; i < 8; i++) { // 增加烟花数量
            setTimeout(() => {
                // 计算结果区域内的随机位置
                const x = rect.left + Math.random() * rect.width;
                const y = rect.top + Math.random() * rect.height;
                this.createFirework(x, y);
            }, i * 200); // 缩短烟花间隔时间
        }

        // 创建第二波烟花
        setTimeout(() => {
            for (let i = 0; i < 8; i++) {
                setTimeout(() => {
                    const x = rect.left + Math.random() * rect.width;
                    const y = rect.top + Math.random() * rect.height;
                    this.createFirework(x, y);
                }, i * 200);
            }
        }, 1000);
    }

    startNextRound() {
        this.currentRound++;
        if (this.currentRound < this.rounds.length) {
            // 清空上一轮的抽奖结果
            const resultBox = document.getElementById('resultBox');
            resultBox.innerHTML = '';
            // 重置结果框的类名，移除列数相关的类
            resultBox.className = 'result-box';

            // 更新轮次信息
            this.updateRoundInfo();
            this.isRoundFinished = false; // 重置标记

            // 显示开始提示
            this.showStartTip();
        } else {
            // 如果是最后一轮结束，可以显示抽奖完成的提示
            const resultBox = document.getElementById('resultBox');
            resultBox.innerHTML = '';
            const endDiv = document.createElement('div');
            endDiv.style.cssText = `
                color: rgba(212, 54, 59, 0.8);
                font-size: 40px;
                text-align: center;
                width: 100%;
                position: absolute;
                top: 50%;
                transform: translateY(-50%);
            `;
            endDiv.textContent = '抽奖已结束';
            resultBox.appendChild(endDiv);
        }
    }

    // 添加获奖记录
    addWinnerRecord(winner, prize) {
        this.allWinners.push({
            group: prize.group,
            round: prize.round,
            groupName: prize.name,
            roundName: prize.subName,
            winner: winner,
            timestamp: new Date().toLocaleString()
        });
    }

    // 导出到Excel的方法
    exportToExcel() {
        // 准备数据
        const data = [
            ['组别', '轮次', '工号', '姓名', '抽奖时间'] // 添加姓名列
        ];

        // 添加所有获奖记录
        this.allWinners.forEach(record => {
            data.push([
                record.groupName,
                record.roundName,
                record.winner.code,
                record.winner.name,
                record.timestamp
            ]);
        });

        // 创建工作簿
        const wb = XLSX.utils.book_new();
        const ws = XLSX.utils.aoa_to_sheet(data);

        // 设置列宽
        const colWidths = [{ wch: 8 }, { wch: 10 }, { wch: 15 }, { wch: 12 }, { wch: 20 }];
        ws['!cols'] = colWidths;

        // 添加工作表到工作簿
        XLSX.utils.book_append_sheet(wb, ws, '抽奖结果');

        // 获取当前轮次信息
        const currentRound = this.rounds[this.currentRound];

        // 生成文件名，包含组次和轮次信息
        const fileName = `抽奖结果_${currentRound.name}${currentRound.subName}_${new Date().toLocaleDateString().replace(/\//g, '')}.xlsx`;

        // 保存文件
        XLSX.writeFile(wb, fileName);
    }

    // 进入全屏
    async enterFullscreen() {
        const elem = document.documentElement;
        try {
            if (elem.requestFullscreen) {
                await elem.requestFullscreen();
            } else if (elem.webkitRequestFullscreen) {
                await elem.webkitRequestFullscreen();
            } else if (elem.mozRequestFullScreen) {
                await elem.mozRequestFullScreen();
            } else if (elem.msRequestFullscreen) {
                await elem.msRequestFullscreen();
            }
            this.isFullscreen = true;
        } catch (error) {
            throw error;
        }
    }

    // 退出全屏
    exitFullscreen() {
        try {
            if (document.exitFullscreen) {
                document.exitFullscreen();
            } else if (document.webkitExitFullscreen) {
                document.webkitExitFullscreen();
            } else if (document.mozCancelFullScreen) {
                document.mozCancelFullScreen();
            } else if (document.msExitFullscreen) {
                document.msExitFullscreen();
            }
            this.isFullscreen = false;
        } catch (error) {
            console.log('退出全屏失败:', error);
        }
    }

    // 切换全屏状态
    toggleFullscreen() {
        if (!this.isFullscreen) {
            this.enterFullscreen();
        } else {
            this.exitFullscreen();
        }
    }

    // 添加控制背景音乐的方法
    toggleBackgroundMusic() {
        const backgroundMusic = document.getElementById('backgroundMusic');
        if (backgroundMusic.paused) {
            backgroundMusic.play().catch(error => {
                console.log('无法播放音乐:', error);
            });
        } else {
            backgroundMusic.pause();
        }
    }
}

// 修改初始化方式
window.onload = () => {
    const lottery = new LotterySystem();
    lottery.init().catch(error => {
        console.log('初始化失败:', error);
    });
};
